import appApi from '@/sheep/api/app';
import {
	defineStore
} from 'pinia';
import {
	cloneDeep
} from 'lodash'
import $platform from '@/sheep/platform';
import $router from '@/sheep/router';
import user from './user';
import sys from './sys';
import updateApi from '@/sheep/api/update';
import Timer from "@/sheep/helper/timer.js";

let msgTimer = null;

// #ifdef APP
// app审核版本控制
let current_version = 100;
// #endif

// #ifdef MP
// 小程序审核版本控制
let current_version = 145;
// #endif

const defTemplate = {
	// 店铺装修模板
	basic: {}, // 基本信息
	home: {
		// 商城模板
		style: {},
		data: [],
	},
	index: {
		// 首页模板
		style: {},
		data: [],
	},
	user: {
		// 个人中心模板
		style: {},
		data: [],
	},
}
const app = defineStore({
	id: 'app',
	state: () => ({
		info: {
			// 应用信息
			name: '', // 商城名称
			logo: '', // logo
			version: '', // 版本号
			cdnurl: '', // 云存储域名
			filesystem: '', // 云存储平台
			user_protocol: {}, // 用户协议
			privacy_protocol: {}, // 隐私协议
			about_us: {}, // 关于我们
			copyright: '', // 版权信息 I
			copytime: '', // 版权信息 II
		},
		platform: {
			payment: [], // 支持的支付方式
			recharge_payment: [], // 支持的充值支付方式
			share: {
				methods: [], // 支持的分享方式
				forwardInfo: {}, // 默认转发信息
				posterInfo: {}, // 海报信息
				linkAddress: '', // 复制链接地址
			},
			auto_login: 0, // 自动登陆
			bind_mobile: 0, // 登陆后绑定手机号提醒 (弱提醒，可手动关闭)
		},
		chat: {},
		template: cloneDeep(defTemplate),
		shareInfo: {}, // 全局分享信息
		dotList: [{
			show: false,
			num: 0
		},
		{
			show: false,
			num: 0
		},
		{
			show: false,
			num: 0
		},
		{
			show: false,
			num: 0
		},
		{
			show: false,
			num: 0
		}
		],
		allConversation: [],
		isAuditMode:false,
		audit_versions:'',
		// 是否是审核版
		updateShow: false,
		// 热更新弹窗显示隐藏
		updatePopShow: false,
		updateData: {},
		unreadNum: 0,
		timeId: null,
		msgTimestamp:0,
		containIm:false,
	}),

	actions: {
		upDateImMsgNum(){
			if((this.msgTimestamp + 5*1000) <= Date.now()){
				this.setUnreadNum()
			}
		},
		openGetMsgNum(){
			if(this.containIm){
				if(!msgTimer){
					msgTimer = new Timer(this.upDateImMsgNum,5000)
				}
				msgTimer.start()
			}
		},
		clearGetMsgNum(){
			if(msgTimer){
				msgTimer.pause()
			}
		},
		unloadGetMsgNum(){
			if(msgTimer){
				msgTimer.reset()
				msgTimer = null
			}
		},
		setUnreadNum() {
			
			const userStore = user();
			if (userStore.isLogin) {
				uni.request({
					url: 'https://im-beta.shisan-xi.work/api/settings/noReadNum',
					method: 'POST',
					data: {
						mobile: userStore.userInfo.mobile,
					},
					success: (res) => {
						if (res.data.code === 0) {
							this.unreadNum = res.data.data.num
						}
					}
				});
			}
		},
		// 获取当前手机类型
		async getPhoneModel(template, refresh) {
			const setTemplate = async (device) => {
				let temp = cloneDeep(template)
				const {
					error,
					data
				} = await updateApi.getUpdate(device)
				if (error === 0) {
					// 本地版本小于后台版本 热更新
					if (Number($platform.device.appVersionCode) < Number(data.version)) {
						if (refresh) {
							return
						}
						uni.showModal({
							title: '温馨提示',
							content: '检测到新版本是否更新？',
							cancelText: "取消",
							confirmText: "去更新",
							showCancel: true,
							confirmColor: '#000',
							cancelColor: '#666',
							success: (res) => {
								if (res.confirm) {
									let url = ''
									if (device === 'huawei') {
										url = `market://details?id=${data.bao}`
									} else {
										url =
											`https://itunes.apple.com/cn/app/id${data.bao}`
									}
									plus.runtime.openURL(url);
								}
							}
						})
					}
					// 本地版本大于后台版本 审核
					if (Number($platform.device.appVersionCode) > Number(data.version)) {
						this.isAuditMode = true;
						this.platform.recharge_payment = this.platform.recharge_payment.filter(item => item !== "wechat")
						temp.home.data = temp.home.data.filter(item => item.type !== 'imageBanner')
						let index = temp.user.data.findIndex(item => item.type === 'menuGrid')
						if (index !== -1) {
							temp.user.data[index].data.list = temp.user.data[index].data.list
								.filter(item => {
									return !['/pages/commission/franchiseInfo?type=2',
										'/pages/commission/franchiseInfo?type=1',
										'/pages/user/wallet/activity'
									].includes(item.url)
								});
						}
						temp.basic.tabbar.list = temp.basic.tabbar.list.filter(item => {
							return !['/association/index', '/im/index'].includes(item.url)
						})
						this.updateShow = true
						this.updatePopShow = false
					}
					this.template = temp
				}
			}

			const setUpdate = async () => {
				let temp = cloneDeep(template)
				const {
					error,
					data
				} = await updateApi.getUpdate('android')
				if (error === 0) {
					if (Number($platform.device.appVersionCode) < Number(data.version)) {
						if (refresh) {
							return
						}
						this.updatePopShow = true
						this.updateData = data.ext[data.ext.length - 1]
					} else {
						this.updatePopShow = false
					}

					if (Number($platform.device.appVersionCode) > Number(data.version)) {
						this.isAuditMode = true;
						this.platform.recharge_payment = this.platform.recharge_payment.filter(item => item !== "wechat")
						temp.home.data = temp.home.data.filter(item => item.type !== 'imageBanner')
						let index = temp.user.data.findIndex(item => item.type === 'menuGrid')
						if (index !== -1) {
							temp.user.data[index].data.list = temp.user.data[index].data.list
								.filter(item => {
									return !['/pages/commission/franchiseInfo?type=2',
										'/pages/commission/franchiseInfo?type=1',
										'/pages/user/wallet/activity'
									].includes(item.url)
								});
						}
						temp.basic.tabbar.list = temp.basic.tabbar.list.filter(item => {
							return !['/association/index', '/im/index'].includes(item.url)
						})
					}
					this.template = temp
				}
			}

			// #ifdef APP
			if ($platform.os === 'android') {
				if ($platform.device.deviceBrand === 'huawei') {
					await setTemplate('huawei')
				} else {
					await setUpdate()
				}
			} else {
				await setTemplate('ios')
			}
			// #endif
			// #ifdef MP || H5
			this.template = template
			// #endif
		},
		// 更新获取消息列表
		upallConversation(data) {
			this.allConversation = data
		},
		// 更新消息总数量
		updotList(data, index) {
			this.dotList[index] = data
		},

		// 获取Shopro应用配置和模板
		async init(templateId = null, refresh = false) {
			//检查网络
			const networkStatus = await $platform.checkNetwork();
			if (!networkStatus) {
				$router.error('NetworkError');
			}
			this.template = cloneDeep(defTemplate)
			this.isAuditMode = false;
			// #ifndef H5
			const config = await appApi.config()
			let { audit_versions, line_versions } = config.data
			if (current_version> Number(line_versions)) {
				this.isAuditMode = true;
				// 审核版本号
				this.audit_versions = audit_versions;
				templateId = Number(audit_versions)
			}
			// #endif
			const res = await appApi.init(templateId);
			if (res.error === 0) {
				this.info = res.data.app;
				this.platform = res.data.platform;
				await this.getPhoneModel(res.data.template, refresh)
				if (!res.data.template) {
					$router.error('TemplateError');
				}
				this.chat = res.data.chat;

				// 加载主题
				
				const sysStore = sys();
				sysStore.setTheme();

				// 模拟用户登录
				const userStore = user();
				if (userStore.isLogin) {
					userStore.loginAfter();
				}
				return Promise.resolve(true);
			} else {
				$router.error('InitError', res.msg || '加载失败');
			}
		},
		// 更新首页地区
		updateRegion(data) {
			this.template.index.style.navbar.list.mp.map(item => {
				if (item.type === 'picker') {
					item.region = data
				}
				return item
			})
		}
	},

	persist: {
		enabled: true,
		strategies: [{
			key: 'app-store',
		},],
	},

});

export default app;